package com.yliyun.watermark;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Watermark {
	public static void main(String[] args) {
		String strPath = "";
		String targetPath = "";
		String text = "";
		//开发测试代码
		if (args == null || args.length < 3) {
			strPath = Watermark.class.getClassLoader().getResource("").getPath() + "testdata";
			targetPath = Watermark.class.getClassLoader().getResource("").getPath() + "testdataout";
			text = "基线";
		} else {
			strPath = args[0];
			targetPath = args[1];
			text = args[2];
		}
		File file=new File(targetPath).getAbsoluteFile();
		if(!file.exists()){
			file.mkdirs();
		}
		List fileList=getFileList(strPath);
		try {
			for(int i=0;i<fileList.size();i++){
				String src=((File)fileList.get(i)).getAbsolutePath();
				String target=targetPath+"/"+((File)fileList.get(i)).getName();
				boolean b=watermark(src, target, text);
				System.out.println(src+"======="+b);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		System.exit(0);
	}


	public static List<File> getFileList(String strPath) {
		List filelist = new ArrayList();
		File dir = new File(strPath);
		File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				if (files[i].isDirectory()) { // 判断是文件还是文件夹
					getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
				} else {
					String strFileName = files[i].getAbsolutePath();
					System.out.println("---" + strFileName);
					filelist.add(files[i]);
				}
			}
		}
		return filelist;

	}

	private static boolean watermark(String src, String target, String text) throws Exception {
		String ext = getFileExt(src);
		if ("pdf".equalsIgnoreCase(ext)) {
			WatermarkPdf.watermark(src, target, text);
			return true;
		} else if ("docx".equalsIgnoreCase(ext)) {
			WatermarkOffice.word2007(src, target, text);
			return true;
		} else if ("doc".equalsIgnoreCase(ext)) {
			WatermarkOffice.word2003(src, target, text);
			return true;
		} else if ("xlsx".equalsIgnoreCase(ext)) {
			WatermarkOffice.excel2007(src, target, text);
			return true;
		} else if ("xls".equalsIgnoreCase(ext)) {
			WatermarkOffice.excel2003(src, target, text);
			return true;
		}
		return false;
	}
	
	private static String getFileExt(String file) {
		int index = file.lastIndexOf(".");
		if (index != -1) {
			return file.substring(index + 1);
		}
		return "";
	}
}
